PARAMETERS AND RETURN VALUES
In Python functions, parameters and return values play a crucial role in passing information to and from functions, respectively. Parameters are placeholders for values that are passed into the function when it is called, while return values are the results that a function provides back to the caller. Let's explore parameters and return values in more detail:
1. Function Parameters: Parameters are defined within the parentheses of the function's definition. When calling a function, you provide specific values (arguments) that will replace these parameters during the function's execution. There are two types of parameters:
a. Positional Parameters: These parameters are defined in the function's signature, and their values are assigned based on the order in which the arguments are passed during the function call.
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")
greet("Alice", 30)
# Output: Hello, Alice! You are 30 years old.
greet("Bob", 25)
# Output: Hello, Bob! You are 25 years old.
b. Keyword Parameters: In this case, you explicitly mention the parameter names during the function call, along with their corresponding values. This allows you to pass arguments out of order or skip some parameters.
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")
greet(age=30, name="Alice")
# Output: Hello, Alice! You are 30 years old.
Note: Keyword parameters must follow positional parameters in the function's signature.
2. Return Values: A function can use the return
statement to send a result back to the caller. The value provided by the return
statement can be assigned to a variable or used directly in the calling code.
def add_numbers(a, b):
result = a + b
return result
sum_result = add_numbers(5, 3)
print(sum_result) # Output: 8
In this example, the function add_numbers()
takes two parameters, a
and b
, and returns their sum as the result.
A function can also have multiple return statements, but as soon as a return statement is encountered, the function terminates, and the value is returned to the caller.
def check_number(n):
if n > 0:
return "Positive"
elif n < 0:
return "Negative"
else:
return "Zero"
num_result = check_number(5)
print(num_result) # Output: Positive
num_result = check_number(-2)
print(num_result) # Output: Negative
num_result = check_number(0)
print(num_result) # Output: Zero
In this case, the function check_number()
returns different strings based on the value of the input parameter n
.
Remember that functions don't necessarily have to return a value. If no return statement is present in a function, it implicitly returns None
.